# Author Zenos
# Create 2025/3/10 上午9:53
import json
from PIL import Image
import os
import numpy as np


def save_dict_json(data, filename):
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=None)


def load_dict_json(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        return json.load(f)


def read_chars_to_dict(file_path):
    char_dict = {}
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read().strip()
        for index, char in enumerate(text):
            char_dict[index + 1] = char  # key 从 1 开始
    return char_dict


def save_char_classes(file_path, classes_path):
    char_dict = load_dict_json(file_path)
    class_dict = {}
    for key in char_dict.keys():
        label = Image.open(os.path.join(classes_path, 'SegmentationClassAug', f'GB{key}_R.png'))
        label_np = np.array(label.copy()).astype(int)
        # 初始化长度为 35 的数组，默认全 0
        class_array = [0] * 35
        # 获取标签中包含的所有类别
        unique_classes = np.unique(label_np).tolist()
        class_dict[key] = unique_classes

    save_dict_json(class_dict, f"char_classes/{os.path.basename(classes_path)}_array.json")


# 示例调用
# file_path = "/Users/zenos/Desktop/GB2312.txt"  # 替换为你的文件路径
# char_dict = read_chars_to_dict(file_path)
# save_dict_json(char_dict, "char_dict.json")
file_path = "char_dict.json"
classes_path = "/Users/zenos/Downloads/CCSSD/HLJ2017"
save_char_classes(file_path, classes_path)







